<?php
namespace control;
/*
*供货清单类
*/

class supplyListClass extends adIndexClass
{
    private const page = 'supplyList';
    private const title = '供货清单';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            case 'supplierMaterialSearch':
                $tr = [
                    'code'          => [
                        'name'  => '物料编码',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName' => [
                        'name'  => "物料名称",
                        'width' => 200
                    ],
                    'model'  => [
                        'name'  => "规格型号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unit'         => [
                        'name'  => '单位',
                        'width' => 200,
                    ],
                    'num'          => [
                        'name'  => '采购批量',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '单价('.static::$unit.')',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'rate'          => [
                        'name'  => '税率',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 200,
                    ]
                ];
                break;
            default:
                $tr = [
                    'supplier'          => [
                        'name'  => '供应商名称',
                        'width' => 200,
                    ],
                    'code' => [
                        'name'  => "物料编码",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'materialName'  => [
                        'name'  => "物料名称",
                        'width' => 200,
                    ],
                    'model'         => [
                        'name'  => '规格型号',
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'unit'          => [
                        'name'  => '单位',
                        'width' => 150,
                    ],
                    'num'          => [
                        'name'  => '采购批量',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'price'          => [
                        'name'  => '单价（' . static::$unit . '）',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'rate'          => [
                        'name'  => '税率',
                        'width' => 150,
                        'sort' => 1,
                    ],
                    'text'          => [
                        'name'  => '备注',
                        'width' => 150,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function supplierMaterialOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "物料编码" => text(array("name" => "code")).
                        hidden(array("name" => "targetId", "value" => $this->get('id'))),
                    "物料名称"   => text(array("name" => "materialName")),
                    "规格型号"   => text(array("name" => "model")),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /**
     * 供应商页卡
     * @return bool|string
     */
    public function supplierMaterial(): bool|string
    {
        $html = $this->supplierMaterialOptions(false);
        $button = "";
        //返回
        $json['html'] = $this->search($html, layout: 'pop', toolButton: $button);
        return json_encode($json, 320);
    }

    public function supplierMaterialSearch(): bool|string
    {
        $targetId = $this->post('targetId');
        //like查询数组
        $like = array(
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
            "c.model" => $this->post('model'),
        );
        //全等查询数组
        $equal = array(
            "a.coid"=>self::$coid,
            "a.state"=>'已通过'
        );
        $and = " and a.supplierId = '$targetId'";
        //生成查询语句
        $where = search([
                "=" => $equal,
                "like" => $like,
            ]) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.list desc,b.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "purchase_contract as a join purchase_contract_detail as b on a.id = b.orderId join material as c on c.id = b.materialId",
            'field'=>"b.*,a.supplierId,c.code,c.name as materialName,c.model,c.unit",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array();
        //获取记录
        foreach ($page['array'] as $array) {
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "num":
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case "price":
                        $row[] = self::lostZero($array['price'],'pricePrecision');
                        break;
                    case "rate":
                        $row[] = ($array['rate']*100).'%';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='invoiceForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "物料编码" => text(array("name" => "code")),
                    "物料名称"   => text(array("name" => "materialName")),
                    "规格型号"   => text(array("name" => "model")),
                ],
                [
                    '供应商'  => supplierClass::supplierSelect(array('title' => '')),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "c.name" => $this->post('materialName'),
            "c.code" => $this->post('code'),
            "c.model" => $this->post('model'),
        );
        //全等查询数组
        $equal = array(
            "a.supplierId" => $this->post('supplierId'),
            "a.coid"=>self::$coid,
            "a.state"=>'已通过'
        );
        $and = "";
        if ($this->post('contractNo')) {
            $and.=" and b.contractId in (select id from sales_contract where orderNo like '%".$this->post('contractNo')."%' and coid = '".self::$coid."')";
        }
        if ($this->post('createTime')) {
            //单据日期
            $timeArr = explode(' ~ ', $this->post('createTime'));
            $and .= " and b.recordDate >='{$timeArr[0]}' and b.recordDate <='{$timeArr[1]}'";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'b.list desc,b.time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array(
            "table" => "purchase_contract as a join purchase_contract_detail as b on a.id = b.orderId join material as c on c.id = b.materialId",
            'field'=>"b.*,a.supplierId,c.code,c.name as materialName,c.model,c.unit",
            "where" => $where,
            "order" => $orderBy['orderBy']
        ));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
            );
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "supplier":
                        $supplier = query('supplier',"id = '$array[supplierId]'");
                        $row[] = $supplier['name'];
                        break;
                    case "num":
                        $row[] = self::lostZero($array['num'],'numPrecision');
                        break;
                    case "price":
                        $row[] = self::lostZero($array['price'],'pricePrecision');
                        break;
                    case "rate":
                        $row[] = ($array['rate']*100).'%';
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        $total_num = find([
            'table'  => "purchase_contract as a join purchase_contract_detail as b on a.id = b.orderId join material as c on c.id = b.materialId",
            'single' => $where,
            'field'  => "ifnull(sum(b.num),0) as num",
        ]);
        $total    = [
            'num'      => self::lostZero($total_num['num'],'numPrecision'),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total"       => $total,
        ));
        //返回
        $json['html'] = "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }   else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => "purchase_contract as a join purchase_contract_detail as b on a.id = b.orderId join material as c on c.id = b.materialId",
                    'field'=>"b.*,a.supplierId,c.code,c.name as materialName,c.model,c.unit",
                    "where" => "b.id in ('".implode("','", $checkedId)."') order by b.list desc,b.time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $supplier = query('supplier',"id = '$array[supplierId]'");
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '供应商名称'=>$supplier['name'],
                            '物料编码'=>$array['code'],
                            '物料名称'=>$array['materialName'],
                            '规格型号'=>$array['model'],
                            '单位'=>$array['unit'],
                            '采购批量'=>self::lostZero($array['num'],'numPrecision'),
                            '单价'=>self::lostZero($array['price'],'pricePrecision'),
                            '税率'=>($array['rate']*100).'%',
                            '备注'=>$array['text'],
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了供货清单";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "供货清单.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'供应商名称',
                    'aliasName'=>'供应商名称',
                ],
                [
                    'columnName'=>'物料编码',
                    'aliasName'=>'物料编码',
                ],
                [
                    'columnName'=>'物料名称',
                    'aliasName'=>'物料名称',
                ],
                [
                    'columnName'=>'规格型号',
                    'aliasName'=>'规格型号',
                ],
                [
                    'columnName'=>'单位',
                    'aliasName'=>'单位',
                ],
                [
                    'columnName'=>'采购批量',
                    'aliasName'=>'采购批量',
                ],
                [
                    'columnName'=>'单价',
                    'aliasName'=>'单价('.static::$unit.')',
                ],
                [
                    'columnName'=>'税率',
                    'aliasName'=>'税率',
                ],
                [
                    'columnName'=>'备注',
                    'aliasName'=>'备注',
                ],
            ]
        };
    }
}

